// index.js
const { readTeamsFromFile, writeTeamsToFile } = require('./utils');
const Team = require('./team');
const readlineSync = require('readline-sync');

const sortTeams = (teams) => {
    return teams.sort((a, b) => {
        if (a.points !== b.points) {
            return b.points - a.points;
        }
        if ((a.goalsScored - a.goalsConceded) !== (b.goalsScored - b.goalsConceded)) {
            return (b.goalsScored - b.goalsConceded) - (a.goalsScored - a.goalsConceded);
        }
        return b.goalsScored - a.goalsScored;
    });
};

const main = () => {
    const teams = readTeamsFromFile('initial_table.txt');

    while (true) {
        const homeTeamName = readlineSync.question("请输入主队名称: ");
        const awayTeamName = readlineSync.question("请输入客队名称: ");
        const homeGoals = parseInt(readlineSync.question("请输入主队得分: "), 10);
        const awayGoals = parseInt(readlineSync.question("请输入客队得分: "), 10);

        let homeTeam, awayTeam;
        for (const team of teams) {
            if (team.name === homeTeamName) {
                homeTeam = team;
            } else if (team.name === awayTeamName) {
                awayTeam = team;
            }
        }

        if (homeTeam && awayTeam) {
            homeTeam.update(homeGoals, awayGoals, true);
            awayTeam.update(homeGoals, awayGoals, false);
        } else {
            console.log("输入的球队名称有误，请重新输入。");
            continue;
        }

        sortTeams(teams);

        console.log("\n当前积分榜:");
        teams.forEach(team => console.log(team.toString()));

        writeTeamsToFile(teams, 'updated_table.txt');

        const continueInput = readlineSync.question("是否继续输入比赛结果？(y/n): ");
        if (continueInput.toLowerCase() !== 'y') {
            break;
        }
    }
};

main();